package com.fr71.project.dm.listener;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class TcpDataReader {
    private final byte[] data;
    private int index = 0;

    public TcpDataReader(byte[] data) {
        this.data = data;
    }

    public int getIndex() {
        return index;
    }

    /**
     * 读取指定字节长度的数据
     * [size] 要读取的字节长度
     */
    public byte[] readByteArray(int size) {
        byte[] result = new byte[size];
        System.arraycopy(data, index, result, 0, size);
        index += size;
        return result;
    }

    public byte[] subByteArray(int startIndex, int dataLength) {
        byte[] result = new byte[dataLength];
        System.arraycopy(data, startIndex, result, 0, dataLength);
        return result;
    }

    /**
     * 读取数字
     * [size] 要读取的字节长度
     */
    public long readNumber(int size) {
        return new BigInteger(1, readByteArray(size)).longValue();
    }

    /**
     * 读取字符串
     * [sizeLength] 要读取字符串的长度在该数据中表示的位置长度
     */
    public String readString(int sizeLength) {
        int size = (int) readNumber(sizeLength);
        return new String(readByteArray(size), StandardCharsets.UTF_8);
    }

    /**
     * 读取指定长度的字符串字符串
     */
    public String readSiString(int size) {
        byte[] bytes = readByteArray(size);
        int i = 0;
        while (i < bytes.length && bytes[i] != 0) {
            i++;
        }
        return new String(bytes, 0, i, StandardCharsets.UTF_8);
    }

    /**
     * 将读取指针向后移动
     * [size] 指针移动的长度
     */
    public void stepSize(int size) {
        this.index = this.index + size;
    }

    /**
     * 将当前指针以后的所有数据都读出来
     */
    public byte[] readLastData() {
        return readByteArray(data.length - this.index);
    }
}